package com.thesis.manage.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.thesis.manage.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;

/**
 * @author php
 * @date 2018/3/28
 */
@Slf4j
public class AliOSSUtil {
    private static final String END_POINT = "oss-cn-hangzhou.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAIryfDgCIobIts";
    private static final String ACCESS_KEY_SECRET = "EOM0m0O6LlAp7GknUGFAXp2hnCELsT";
    private static final String BUCKET_NAME = "document-thesis";
    // 文件访问域名
    private static final String FILE_HOST = "https://document-thesis.oss-cn-hangzhou.aliyuncs.com/";

    /**
     * 方法描述:上传文件
     *
     * @param file 文件
     * @return string
     * @author leon 2016年12月26日 下午3:33:13
     */
    public static String upload(MultipartFile file) {
        if (file == null) {
            throw new CommonException("file is null", "请选择上传文件");
        }
        // 创建OSS客户端
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 判断文件容器是否存在，不存在则创建
            if (!ossClient.doesBucketExist(BUCKET_NAME)) {
                ossClient.createBucket(BUCKET_NAME);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(BUCKET_NAME);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            // 创建文件路径
            LocalDate now = LocalDate.now();
            String fileUrl = now.getYear() + "/" + now.getMonthValue() + "/" + now.getDayOfMonth() + "/" + file.getOriginalFilename();
            // 上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(BUCKET_NAME, fileUrl, file.getInputStream()));
            if (null != result) {
                return FILE_HOST + fileUrl;
            }
        } catch (Exception oe) {
            throw new CommonException("file upload error", "文件上传失败");
        } finally {
            // 关闭OSS服务，一定要关闭
            ossClient.shutdown();
        }
        return null;

    }

}